package homework.nettygateway;

import homework.client.HttpClient;
import homework.filter.HeaderHttpRequestFilter;
import homework.router.GetServerByIdx;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;

import java.util.ArrayList;

public class HttpHandler extends ChannelInboundHandlerAdapter {

    private ArrayList<String> servers = new ArrayList<>();

    public HttpHandler() {
        servers.add("http://localhost:8801");
        servers.add("http://localhost:8802");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            HeaderHttpRequestFilter requestFilter = new HeaderHttpRequestFilter(servers);
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            // 对请求头的server，进行赋值，之后会根据该值来进行转发
            requestFilter.filter(fullHttpRequest, servers, ctx);
            handlerTest(fullHttpRequest, ctx, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    private void handlerTest(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx, String body) {
        FullHttpResponse response = null;
        try {
            int serverIdx = fullHttpRequest.headers().getInt("server");
            System.out.println("=========此次分发到第" + serverIdx + "个url上, 即 "
                    + servers.get(serverIdx) + " ========");
            GetServerByIdx getServerByIdx = new GetServerByIdx();
            String url = getServerByIdx.route(servers, serverIdx);

            // 进行服务请求
            String value = HttpClient.run(url);

            // TODO 这里使用okhttp会直接跳到finally, 暂时不知道原因
//            OkHttp okHttp = new OkHttp();
//            String value = okHttp.run(url);

            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
            response.headers().set("Content-Type", "application/json");
            response.headers().setInt("Content-Length", response.content().readableBytes());
        } catch (Exception e) {
            System.out.println("处理错误:" + e.getMessage());
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        } finally {
            if (fullHttpRequest != null) {
                if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else {
                    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                    ctx.write(response);
                }
                ctx.flush();
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
